import { createRouter, createWebHashHistory } from 'vue-router'
import pinia from "../store";
import { useRouterStore, useIndexStore } from "../store/path";
import { vToast } from "@/plugins/vToast";
const routerStore = useRouterStore(pinia);
const indexStore = useIndexStore(pinia);

// 导入统一布局组件
const UnifiedLayout = () => import('@/views/common/layout.vue');

const routes = [
  // 公共路由
  {
    path: '/user/login',
    name: 'login',
    component: () => import('@/views/user/login.vue'),
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/notFound/index.vue'),
  },

  // 主应用路由 - 使用统一布局
  {
    path: '/',
    name: 'app',
    component: UnifiedLayout,
    redirect: '/admin/index',
    children: [
      // 管理员后台路由
      {
        path: 'admin/index',
        name: 'adminIndex',
        component: () => import('@/views/admin/index/index.vue'),
      },
      {
        path: 'admin/calendar',
        name: 'adminCalendar',
        component: () => import('@/views/admin/calendar/calendar.vue'),
      },
      {
        path: 'admin/staff',
        name: 'staff',
        component: () => import('@/views/admin/staff/index.vue'),
        meta: { requiresAdmin: true },
      },
      {
        path: 'admin/settings',
        name: 'settings',
        component: () => import('@/views/admin/settings/index.vue'),
        meta: { requiresAdmin: true },
      },
      {
        path: 'admin/category',
        name: 'category',
        component: () => import('@/views/admin/category/index.vue'),
      },
      {
        path: 'admin/source',
        name: 'source',
        component: () => import('@/views/admin/source/index.vue'),
      },
      {
        path: 'admin/payMethod',
        name: 'payMethod',
        component: () => import('@/views/admin/payMethod/index.vue'),
      },
      {
        path: 'admin/money',
        name: 'money',
        component: () => import('@/views/admin/money/index.vue'),
      },
      {
        path: 'admin/dict',
        name: 'adminDict',
        component: () => import('@/views/dict/index.vue'),
      },
      {
        path: 'admin/order/list',
        name: 'orderList',
        component: () => import('@/views/admin/order/list.vue'),
      },
      {
        path: 'admin/order/modify/:id?',
        name: 'orderModify',
        component: () => import('@/views/admin/order/modify.vue'),
        props: true,
      },
      {
        path: 'admin/order/create',
        name: 'orderCreate',
        component: () => import('@/views/admin/order/create.vue'),
      },
      {
        path: 'admin/material/list',
        name: 'materialList',
        component: () => import('@/views/admin/material/list.vue'),
        meta: { title: '素材列表' },
      },
      // 职位管理路由
      {
        path: 'admin/position/list',
        name: 'positionList',
        component: () => import('@/views/admin/position/list.vue'),
        meta: { title: '职位管理' },
      },
      {
        path: 'admin/material/detail/:id?',
        name: 'materialDetail',
        component: () => import('@/views/admin/material/detail.vue'),
        meta: { title: '素材详情' },
        props: true,
      },

      // 员工工作台路由
      {
        path: 'workspace/main',
        name: 'workMain',
        component: () => import('@/views/workspace/main/index.vue'),
      },
      {
        path: 'workspace/finance',
        name: 'workFinance',
        component: () => import('@/views/workspace/finance/index.vue'),
      },
      {
        path: 'workspace/messages',
        name: 'workMessages',
        component: () => import('@/views/workspace/messages/index.vue'),
      },
      {
        path: 'workspace/orders',
        name: 'workOrders',
        component: () => import('@/views/workspace/orders/index.vue'),
      },
      {
        path: 'workspace/task',
        name: 'workTask',
        component: () => import('@/views/task/index.vue'),
      },
      {
        path: 'workspace/calendar',
        name: 'workCalendar',
        component: () => import('@/views/calendar/index.vue'),
      },
      {
        path: 'workspace/dict',
        name: 'workDict',
        component: () => import('@/views/dict/index.vue'),
      },

      // 用户通用路由
      {
        path: 'dict/index',
        name: 'dictIndex',
        component: () => import('@/views/dict/index.vue'),
      },
    ],
  },
  // 路由未匹配时重定向到404页面
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
];

const router = createRouter({
  history: createWebHashHistory(),
  linkActiveClass: "active",
  routes: routes,
  scrollBehavior() {
    return { top: 0 };
  },
});

// 路由守卫
router.beforeEach((to, from, next) => {
  routerStore.$patch({
    currentPage: to.name,
  });

  // 获取当前token状态
  const tokenInStore = indexStore.token;
  const tokenInStorage = localStorage.getItem("token");

  // 同步token逻辑
  if (tokenInStore) {
    // 当store有token时同步到localStorage
    localStorage.setItem("token", tokenInStore);
  } else if (tokenInStorage) {
    // 当localStorage有token时同步到store
    indexStore.$patch({ token: tokenInStorage });
  }

  // 同步后检查登录状态
  const hasToken = indexStore.token || localStorage.getItem("token");

  // 允许访问登录页面和404页面
  if (to.path === '/user/login' || to.path === '/404') {
    return next();
  }

  if (!hasToken) {
    // 无token时重定向到登录页
    return next("/user/login");
  }

  // 检查管理员权限
  if (to.meta.requiresAdmin) {
    const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    if (!["superadmin", "admin"].includes(userInfo.permission)) {
      console.error("无权限访问此页面");
      // 对于无权限的管理员页面，重定向到管理员首页
      if (to.path.startsWith('/admin')) {
        return next("/admin/index");
      }
      // 其他情况重定向到工作台首页
      return next("/workspace/main");
    }
  }

  next();
});

export default router;
